
package com.google.code.sms.android.parser;

import android.content.Context;
import com.google.code.sms.android.R;
import org.xmlpull.v1.XmlPullParser;

import com.google.code.sms.android.domain.IndexElement;
import com.google.code.sms.android.domain.MediaElement;
import com.google.code.sms.android.domain.SearchResult;
import com.google.code.sms.android.util.ProgressListener;

import java.io.Reader;
import java.util.Collections;
import java.util.List;
import java.util.ArrayList;

/**
 * @author Sindre Mehus
 */
public class SearchResultParser extends MediaElementEntryParser {

    public SearchResultParser(Context context) {
        super(context);
    }

    public SearchResult parse(Reader reader, ProgressListener progressListener) throws Exception {
        updateProgress(progressListener, R.string.parser_reading);
        init(reader);

        List<MediaElement.Entry> songs = new ArrayList<MediaElement.Entry>();
        int eventType;
        do {
            eventType = nextParseEvent();
            if (eventType == XmlPullParser.START_TAG) {
                String name = getElementName();
                if ("match".equals(name)) {
                    songs.add(parseEntry());
                } else if ("error".equals(name)) {
                    handleError();
                }
            }
        } while (eventType != XmlPullParser.END_DOCUMENT);

        validate();
        updateProgress(progressListener, R.string.parser_reading_done);

        return new SearchResult(Collections.<IndexElement>emptyList(), Collections.<MediaElement.Entry>emptyList(), songs);
    }

}
